<?php


namespace app\base\service;

use think\admin\service\AdminService;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\Cache;

/**
 * 阿里百炼服务
 * Class AdminService
 * @package think\admin\service
 */
class CozeService extends AdminService
{

    protected $authorization = '';
    private $privateKey="-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDHwQ6cPRlIniAM
JfyY+vCXF0HJKOcxRAgNh8e2rGr0yOJ5g/Ma4RzrQTXAKm++xCC5MfsedvkHNm6o
Lhy2cJCD+iGuXTwQ9yVQwxf3QnCYR9LpPJEIbKlcR/QCWB/qZgtyFcmmBCGfVM16
2VIrKM5qHyrrmdMyxgaM95xgD7r4TonQ0ZbzP7RxJA1tYcKBpcybEmmOGIoSyX/V
3RkUU5iKg37ltW7CSBN6BmfIfJ7zYMZ1mnAaZA63Zqb9NYlBDqWzVHNAegRFMWnG
l3PMT3NM9TGlL2mHODhnxc93NFG0X/jt90FLvQKcqmsU7Cn899DmCiNehKxut5o9
BO2UWtoXAgMBAAECggEAYfVX/+CqpIT+/FYooLD3CXFbTpXjgrJ1LIV4uCmnrfFR
tvuxXW4l62yoOlvVPv0Zexh6qL75csML0ygB5qofBMnGeKa6TSuWPhveheAsLVGT
qdOM4E/BYkLa88dZp25xkHoE0IhYILXKqsMmW4oAZ+Ru/OkLvGuGTN0k76rnKtsj
RBEeQfwSlAL88vSxkdnJ5vzWKol8vuDWD0CJWTt+itnVBIgW3apFfbChxZtHuYGY
HVNLjQ03ZXr+Gv/Y17rG8XojSSBOe8ded7GiuWpvhaYv/DbmvNpo9bWDM+CPwxTm
eXbSJiySIaoSZZ6h9dGh0519owy3RVU3DdjbuRd00QKBgQDlO9BCr8x9Ojr+6q+4
oIBa2GDn+dWSwbyE72zG9KCElCUub3CucK76vqrQ8+1eqZT/hRSumxRFTodziEMj
YWJPePTXDeREsgaWLsKdO/FFcKmF/CRwpmO4Kj+StFzWhfe7NOIdgLtTTzFGIkhP
jJWFWcLMTiAbQZE042bL92qQXwKBgQDfFAzeUahfTb4fnNlFn6TYTxHYsZnVoMWS
HVbqEtpC9qTrsFXhtCUWV7GWgoHwNLFwRMb4NXlpDfvKyJeHqIoq+U+6oZwlzVkG
HfvdgmUyeMlBhrBhzvRdMQ4EKfCVQT+AahRSjMh5juY+9RG7Ohpe0HXAohXNe2Xw
1vQ3gJqxSQKBgQCi8LlALaW0/cchm7/8BFo4OMXpHnTpNDzEYUt4wDm5A3TKZPw7
gm1eXlkc3cZEG1aFqhrhYeouuXsebCUM6RPwWZHvqzgufDyiU+qRySHesg5N5sQg
LqWDKsS1iu7SrbdBon13ayG8PfZQW936bXt6pisI/h9kQF7usRVItj1REQKBgQCz
asbm0DphXH+7oUVGsB2/M+kgpccagJIm8J4E6WDOVt1SCqMoQuFJVQKqERE9BsRn
jYmR/EBH9E09TZRCMZXe9mHfszeJV91wBBGcmNGXhHopz5BxOihkA55ITwsGoFHY
kHkD4+MhkYMxw52dPiATfgoXAsYSXFsjF1+YfEDusQKBgQCS9dKSRGhTZm4UxNhz
9837/++aZLh5OrqxEKZ/QwGdK93vilXu6tHYKECPE6EyjqDozBDMqb5Uu2/vwlaD
dewyTF+kJfh8sjSpjoZcevE6kvwYnadVv/stxrefqlBv5+jJE57Hl0GEpeEIeVei
Ufpy0UjE//NhyUZHml9jnQvGIA==
-----END PRIVATE KEY-----";
    private $appId="1169556038952";
    private $keyId="7brKAbdp_xTGN7nOuu1D0iuJOKZp8lx0FwbnmrClzcg";
    private $audience = 'api.coze.cn';
    private $algorithm = 'RS256';

    protected $url = 'https://api.coze.cn/';

    public function getAuthorization($flag=false)
    {
       // $this->authorization = sysconf("coze_token")??'';
        $cache = RedisService::instance()->store();
        if($cache->get("coze_token".$this->appId) && !$flag){
            return $cache->get('coze_token'.$this->appId);
        }else{
            $jwt = $this->generateJWT();
            $url = "https://api.coze.cn/api/permission/oauth2/token";
            $options['headers'] = ['Authorization:Bearer '.$jwt,'Content-Type: application/json'];
            $data = [
                "grant_type"=>"urn:ietf:params:oauth:grant-type:jwt-bearer",
                "duration_seconds"=>3600,
            ];
            $options['timeout'] = 180;
            $r = http_post($url,json_encode($data),$options);
            $res = json_decode($r,true);
            if(!$res){
                return $this->resulet(0,'请求失败');
            }
            if(isset($res['access_token'])){
                $expire_in = $res['expires_in']-time()-30;
                $cache->set("coze_token".$this->appId,$res['access_token'],$expire_in);

                return  $res['access_token'];
            }else{
                return $this->resulet(0,$res['error_message']);
            }
        }

        dump($res);


    }
    private function generateJWT() {
        // 1. 准备Header
        $header = [
            'alg' => $this->algorithm,
            'typ' => 'JWT',
            'kid' => $this->keyId
        ];

        // 2. 准备Payload
        $currentTime = time();
        $payload = [
            'iss' => $this->appId,          // 应用ID
            'aud' => $this->audience,       // 固定接收方
            'iat' => $currentTime,          // 签发时间
            'exp' => $currentTime + 3600, // 过期时间
            'jti' => bin2hex(random_bytes(16)) // 32字节防重放令牌
        ];


        // 5. 生成JWT（使用Firebase JWT库）
        return JWT::encode($payload, $this->privateKey, $this->algorithm, null, $header);
    }


    protected function resulet($code=0,$msg='',$data=[])
    {
        return [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
    }

    //运行工作流
    public function runWorkflow($workflow_id,$data)
    {
        $retryCount = 0;
        do{
            $authorization = $this->getAuthorization();
            if(is_array($authorization)){
                return $authorization;
            }
            // $authorization = sysconf("coze_token");
            // $authorization = 'pat_E8HA64vECmZW8GbkLZ8XK6tKZ8NRcq9dG7noWbXBLFvwPnm9mz1KfOrswnz70rod';
            $url = $this->url."v1/workflow/run";
            $data = [
                "workflow_id"=>$workflow_id,
                "parameters"=>$data,
                'is_async'=>true
            ];
            $options['headers'] = ['Authorization:Bearer '.$authorization,'Content-Type: application/json'];
            $options['timeout'] = 180;
            $r = http_post($url,json_encode($data),$options);
            $res = json_decode($r,true);
//        $this->app->log->error('runWorkflowParms：'.json_encode($data));
//        $this->app->log->error('runWorkflow：'.$r);
            if(empty($res)){
                return  $this->resulet(0,'接口请求失败');
            }else{
                if($res['code']==0){
                    return  $this->resulet(1,'',$res['execute_id']);
                }else{


                }
            }

        }while($retryCount < 10);

        return  $this->resulet(0,'接口请求失败');



    }

    //查询工作流运行结果
    public function getWorkflowResult($execute_id,$workflow_id)
    {
        $retryCount = 0;
        do{
            $authorization = $this->getAuthorization();
            if(is_array($authorization)){
                return $authorization;
            }

            //$authorization = sysconf("coze_token");
            // $authorization = 'pat_E8HA64vECmZW8GbkLZ8XK6tKZ8NRcq9dG7noWbXBLFvwPnm9mz1KfOrswnz70rod';
            $url ="https://api.coze.cn/v1/workflows/{$workflow_id}/run_histories/{$execute_id}";
            $options['headers'] = ['Authorization:Bearer '.$authorization,'Content-Type: application/json'];
            $options['timeout'] = 180;
            $res = http_get($url,[],$options);
            $res = json_decode($res,true);
            if(empty($res)){
                return  $this->resulet(0,'接口请求失败');
            }else{
                if($res['code']==0){
                    return  $this->resulet(1,'',$res['data']);
                }else{
                    if($res['code']==4008 || $res['code']==4009 ||  $res['code']==5000){
                        sleep(60);
                        $retryCount++;
                    }else{
                        if(strpos($res['msg'], 'token') !== false){
                            $this->getAuthorization(true);
                        }else{
                            return  $this->resulet(0,$res['msg']);
                        }
                    }
                }
            }
        }while($retryCount < 10);
        return  $this->resulet(0,'接口请求失败');
    }




}
